<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use app\common\trait\SettingsTrait;
use FormBuilder\Factory\Elm;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageMch;
use plugin\ycMassage\app\model\MassageMchThumb;
use plugin\ycMassage\app\model\MassageRegions;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\validate\MassageMch as ValidateMassageMch;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\Str;
use support\Request;
use think\facade\Db;
use think\facade\Session;

class MchController extends BaseController
{
    use SettingsTrait;

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize()
    {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
    }
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 240
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('title', 'input', '商户搜索', [
            'placeholder' => '商户名称搜索'
        ]);
        $builder->addScreen('examine', 'select', '审核状态', [
            'options' => Examine::getOptions()
        ]);

        $builder->addTopButton('add', '创建商户', [
            'api'       => $this->pluginPrefix . '/admin/Mch/create',
            'path' => '/Mch/create',
            'type'      => 'modal'
        ], [
            'title' => '创建商户',
        ], [
            'type' => 'success'
        ]);
        $builder->addRightButton('examine', '审核', [
            'api'    => $this->pluginPrefix . '/admin/Mch/examine',
            'path' => '/Mch/examine',
            'type'      => 'modal',
            'params' => [
                'field' => 'examine',
                'where' => '=',
                'value' => 0
            ]
        ], [], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addRightButton('edit', '修改', [
            'api'    => $this->pluginPrefix . '/admin/Mch/update',
            'path' => '/Mch/update',
            'type'      => 'modal'
        ], [], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('shop', '门店', [
            'api'    => $this->pluginPrefix . '/admin/Shop/index',
            'path' => '/Shop/index',
            'aliasParams' => [
                'id' => 'mch_id'
            ]
        ], [], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->addRightButton('thumb', '图册', [
            'api'    => $this->pluginPrefix . '/admin/MchThumb/index',
            'path' => '/MchThumb/index',
            'aliasParams' => [
                'id' => 'mch_id'
            ]
        ], [], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->addRightButton('control', '管理', [
            'type'   => 'link',
            'api'    => $this->pluginPrefix . '/admin/Mch/control'
        ], [], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90
        ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('nickname', '昵称', [
                'width' => 120,
            ])
            ->addColumn('title', '商户名称', [
                'width' => 120,
            ])
            ->addColumn('tel', '商户联系电话', [
                'width' => 120,
            ])
            ->addColumn('name', '负责人', [
                'width' => 120,
            ])
            ->addColumn('mobile', '联系电话', [
                'width' => 120,
            ])
            ->addColumn('province', '省', [
                'width' => 120,
            ])
            ->addColumn('city', '市', [
                'width' => 120,
            ])
            ->addColumn('area', '区', [
                'width' => 120,
            ])
            ->addColumn('street', '街道', [
                'width' => 120,
            ])
            ->addColumnEle('examine', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => Examine::dictOptions(),
                    'style' => Examine::dictOptions('style')
                ],
            ])
            ->addColumn('message', '审核结果');
        $single_mch = getHpConfig('single_mch', $request->saas_appid, 'system');
        if ($single_mch) {
            $builder->addColumnEle('is_default', '默认', [
                'width' => 100,
                'params' => [
                    'type' => 'switch',
                    'api' => $this->pluginPrefix . '/admin/Mch/setDefault',
                    'checked' => State::YES,
                    'unchecked' => State::NO
                ],
            ]);
        }
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['m.saas_appid', '=', $request->saas_appid]
        ];
        $name = $request->get('name');
        if ($name) {
            $where[] = ['m.name|m.title|m.mobile', 'like', "%{$name}%"];
        }
        $examine = $request->get('examine');
        if ($examine !== null) {
            $where[] = ['m.examine', '=', $examine];
        }
        $data = MassageMch::where($where)
            ->alias('m')
            ->join('massage_user u', 'u.id = m.uid')
            ->order('m.create_time desc')
            ->field('m.*,u.headimg,u.nickname')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                $item->nickname = base64_decode($item->nickname);
                if (strpos($item->headimg, 'http') !== 0) {
                    $item->headimg = UploadService::url($item->headimg);
                }
                $item->tel = implode(',', $item->tel);
            });
        return $this->successRes($data);
    }
    public function create(Request $request)
    {
        $saas_appid = $request->saas_appid;
        if ($request->method() === 'POST') {
            $D = $request->post();
            $tel = [];
            if ($D['tel1']) {
                $tel[] = $D['tel1'];
            }
            if ($D['tel2']) {
                $tel[] = $D['tel2'];
            }
            if ($D['tel3']) {
                $tel[] = $D['tel3'];
            }
            $D['tel'] = $tel;
            hpValidate(ValidateMassageMch::class, $D, 'admin_create');
            Db::startTrans();
            try {
                $mobile = $D['mobile'];
                $userModel = MassageUser::where(['mobile' => $mobile, 'saas_appid' => $saas_appid])->find();
                if (!$userModel) {
                    $userModel = new MassageUser;
                    $userModel->saas_appid = $saas_appid;
                    $userModel->mobile = $mobile;
                    $userModel->nickname = $D['title'] . '商户';
                    $userModel->password = $D['password'];
                    $userModel->headimg = $D['logo'][0];
                    $userModel->save();
                }
                $MassageMch = new MassageMch;
                $MassageMch->uid = $userModel->id;
                $MassageMch->saas_appid = $saas_appid;
                $MassageMch->title = $D['title'];
                $MassageMch->logo = $D['logo'][0];
                $MassageMch->address = $D['address'];
                $MassageMch->examine = $D['examine'];
                $MassageMch->name = $D['name'];
                $MassageMch->mobile = $D['mobile'];
                $MassageMch->tel = $tel;
                list($province_id, $city_id, $area_id, $street_id) = $D['regions'];
                $MassageMch->province_id = (int)$province_id;
                $MassageMch->province = MassageRegions::where(['id' => $province_id])->value('title');
                $MassageMch->city_id = $city_id;
                $MassageMch->city = MassageRegions::where(['id' => $city_id])->value('title');
                $MassageMch->area_id = $area_id;
                $MassageMch->area = MassageRegions::where(['id' => $area_id])->value('title');
                if ($street_id) {
                    $MassageMch->street_id = $street_id;
                    $MassageMch->street = MassageRegions::where(['id' => $street_id])->value('title');
                }
                $MassageMch->save();
                if (!empty($D['thumb'])) {
                    $MassageMchThumb = new MassageMchThumb;
                    $thumb = [];
                    foreach ($D['thumb'] as $key => $value) {
                        $temp = [
                            'mch_id' => $MassageMch->id,
                            'saas_appid' => $saas_appid,
                            'url' => $value,
                        ];
                        krsort($temp);
                        $thumb[] = $temp;
                    }
                    $MassageMchThumb->saveAll($thumb);
                }
                Db::commit();
                return $this->success('添加成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $this->getFormBuilder($builder, $saas_appid);
        $builder->addDivider('负责人信息');
        $builder->addRow('name', 'input', '负责人', '', [
            'col' => 12,
        ]);
        $builder->addRow('mobile', 'input', '手机号', '', [
            'col' => 12,
            'prompt' => [
                'text' => '手机号将作为登录账号，如已存在并且未被商户绑定将直接关联',
            ],
        ]);
        $builder->addRow('password', 'input', '登录密码', '', [
            'col' => 12,
        ]);
        $builder->addDivider('商户图册');
        $builder->addComponent('thumb', 'uploadify', '商户图册', '', [
            'col' => 24,
            'props' => [
                'type' => 'image',
                'limit' => 99,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function update(Request $request)
    {
        $id = $request->get('id');
        $saas_appid = $request->saas_appid;
        $MassageMch = MassageMch::where(['id' => $id, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageMch) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $tel = [];
            if ($D['tel1']) {
                $tel[] = $D['tel1'];
            }
            if ($D['tel2']) {
                $tel[] = $D['tel2'];
            }
            if ($D['tel3']) {
                $tel[] = $D['tel3'];
            }
            $D['tel'] = $tel;
            hpValidate(ValidateMassageMch::class, $D, 'admin_update');
            Db::startTrans();
            try {
                $MassageMch->title = $D['title'];
                $MassageMch->logo = $D['logo'][0];
                $MassageMch->address = $D['address'];
                $MassageMch->examine = $D['examine'];
                $MassageMch->name = $D['name'];
                $MassageMch->mobile = $D['mobile'];
                $MassageMch->tel = $tel;
                list($province_id, $city_id, $area_id, $street_id) = $D['regions'];
                $MassageMch->province_id = (int)$province_id;
                $MassageMch->province = MassageRegions::where(['id' => $province_id])->value('title');
                $MassageMch->city_id = $city_id;
                $MassageMch->city = MassageRegions::where(['id' => $city_id])->value('title');
                $MassageMch->area_id = $area_id;
                $MassageMch->area = MassageRegions::where(['id' => $area_id])->value('title');
                if ($street_id) {
                    $MassageMch->street_id = $street_id;
                    $MassageMch->street = MassageRegions::where(['id' => $street_id])->value('title');
                } else {
                    $MassageMch->street_id = null;
                    $MassageMch->street = '';
                }
                $MassageMch->save();
                Db::commit();
                return $this->success('保存成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $this->getFormBuilder($builder, $saas_appid);
        $builder->addDivider('负责人信息');
        $builder->addRow('name', 'input', '负责人', '', [
            'col' => 12,
        ]);
        $builder->addRow('mobile', 'input', '手机号', '', [
            'col' => 12,
        ]);
        $regions = [
            $MassageMch->province_id,
            $MassageMch->city_id,
            $MassageMch->area_id
        ];
        if ($MassageMch->street_id) {
            $regions[] = $MassageMch->street_id;
        }
        $MassageMch->regions = $regions;
        foreach ($MassageMch->tel as $key => $value) {
            $MassageMch->{'tel' . ($key + 1)} = $value;
        }
        $data = $builder->setData($MassageMch)->create();
        return $this->successRes($data);
    }
    public function getFormBuilder($builder, $saas_appid)
    {
        $builder->addRow('title', 'input', '商户名称', '', [
            'col' => 12,
        ]);
        $builder->addComponent('logo', 'uploadify', '商户logo', '', [
            'col' => 12,
            'props' => [
                'type' => 'image',
                'limit' => 1,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $builder->addRow('tel1', 'input', '商户联系电话1', '', [
            'col' => 12,
        ]);
        $builder->addRow('tel2', 'input', '商户联系电话2', '', [
            'col' => 12,
        ]);
        $builder->addRow('tel3', 'input', '商户联系电话3', '', [
            'col' => 12,
        ]);
        $regions = MassageRegions::getCache($saas_appid);
        $builder->addRow('regions', 'city', '地区', [], [
            'col' => 12,
            'options' => $regions,
            'props' => [
                'filterable' => true,
                'placeholder' => '请选择地区',
                'clearable' => true,
                'props' => [
                    'value' => 'id',
                    'label' => 'title',
                    'children' => 'children'
                ]
            ]
        ]);
        $builder->addRow('address', 'input', '详细地址', '', [
            'col' => 12,
        ]);
        $builder->addRow('examine', 'radio', '状态', Examine::WAIT['value'], [
            'col' => 12,
            'options' => Examine::getOptions(),
        ]);
    }
    public function examine(Request $request)
    {
        $id = $request->get('id');
        $MassageMch = MassageMch::where(['id' => $id, 'saas_appid' => $request->saas_appid, 'examine' => Examine::WAIT['value']])->find();
        if (!$MassageMch) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $MassageMch->examine = $D['examine'];
            Db::startTrans();
            try {
                if (!in_array($MassageMch->examine, [Examine::YES['value'], Examine::NO['value']])) {
                    throw new \Exception('请选择审核状态');
                }
                if ($MassageMch->examine == Examine::NO['value']) {
                    if (empty($D['message'])) {
                        throw new \Exception('请填写驳回理由');
                    }
                    $MassageMch->message = $D['message'];
                } else {
                    $MassageMch->message = '通过';
                }
                $MassageMch->save();
                if ($D['thumb_examine'] == Examine::YES['value']) {
                    $thumb = MassageMchThumb::where(['mch_id' => $MassageMch->id, 'saas_appid' => $MassageMch->saas_appid])->select();
                    foreach ($thumb as $key => $itme) {
                        $itme->examine = Examine::YES['value'];
                        $itme->save();
                    }
                }
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addComponent('logo', 'el-image', '商户LOGO', '', [
            'col'           => 6,
            'props'         => [
                'src'       => $MassageMch->logo,
                'width'     => 160,
                'height'    => 220
            ]
        ]);
        $builder->addComponent('id', 'info', '商户ID', '', [
            'col'           => 4,
        ]);
        $builder->addComponent('title', 'info', '商户名称', '', [
            'col'           => 14,
        ]);
        foreach ($MassageMch->tel as $key => $value) {
            $builder->addComponent('tel' . ($key + 1), 'info', '商户联系电话' . ($key + 1), $value, [
                'col'           => 8,
            ]);
        }
        $builder->addDivider('商户详细地址');
        $address_info = [
            $MassageMch->province,
            $MassageMch->city,
            $MassageMch->area,
        ];
        if ($MassageMch->street) {
            $address_info[] = $MassageMch->street;
        }
        $address_info[] = $MassageMch->address;
        $builder->addComponent('address_info', 'info', '', implode(" ", $address_info), [
            'col'           => 24,
        ]);
        $builder->addDivider('商户负责人信息');
        $builder->addComponent('name', 'info', '负责人', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('mobile', 'info', '负责人电话', '', [
            'col'           => 6,
        ]);
        $builder->addDivider('商户图册');
        $builder->addRow('thumb_examine', 'radio', '商户图册状态', 0, [
            'col' => 24,
            'options' => Examine::getOptions()
        ]);
        $thumb = MassageMchThumb::where(['mch_id' => $MassageMch->id, 'saas_appid' => $MassageMch->saas_appid])->field('url')->select();
        foreach ($thumb as $key => $itme) {
            $builder->addComponent('thumb_' . $key, 'el-image', '', '', [
                'col'           => 4,
                'props'         => [
                    'src'       => $itme->url,
                    'width'     => 160,
                    'height'    => 220
                ]
            ]);
        }
        $builder->addDivider('审核');
        $builder->addRow('examine', 'radio', '状态', Examine::YES['value'], [
            'col' => 24,
            'options' => Examine::getOptions(),
            'control' => [
                [
                    'value' => Examine::NO['value'],
                    'where' => '==',
                    'rule' => [
                        Elm::textarea('message', '驳回理由')
                            ->col([
                                'span' => 24
                            ])
                            ->props([
                                'filterable' => true,
                                'placeholder' => '请输入驳回理由',
                            ])
                    ],
                ],
            ]
        ]);
        $data = $builder->setData($MassageMch)->create();
        return $this->successRes($data);
    }
    public function setDefault(Request $request)
    {
        $id = $request->post('id');
        $saas_appid = $request->saas_appid;
        Db::startTrans();
        try {
            $MassageMch = MassageMch::where(['id' => $id, 'saas_appid' => $saas_appid])->find();
            if (!$MassageMch) {
                throw new \Exception('数据不存在');
            }
            $Default = MassageMch::where(['saas_appid' => $saas_appid, 'is_default' => State::YES['value']])->find();
            if ($Default) {
                if ($Default->id == $MassageMch->id) {
                    throw new \Exception('已经是默认商户');
                }
                $Default->is_default = State::NO['value'];
                $Default->save();
            }
            $MassageMch->is_default = State::YES['value'];
            $MassageMch->save();
            Db::commit();
            return $this->success('设置成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
    }
    public function control(Request $request)
    {
        $MassageMch = MassageMch::where(['id' => $request->get('id'), 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageMch) {
            return $this->fail('数据不存在');
        }
        $UserModel = MassageUser::where(['id' => $MassageMch->uid])->find();
        if (!$UserModel) {
            return $this->fail('数据不存在');
        }
        if(!$UserModel->mobile){
            return $this->fail('请先绑定用户手机号');
        }
        Session::set($request->plugin . '_shop', $UserModel);
        $token = Str::random(32);
        return $this->successRes([
            'url' => $this->pluginPrefix . '/shop/#/?appid=' . $request->saas_appid . '&token=' . $token
        ]);
    }
}
